const express = require('express');
const router = express.Router();
const { User } = require('../models');
const { failure, success } = require('../utils/responses');
const { NotFoundError, BadRequestError, UnauthorizedError } = require('../utils/errors');
const bcrypt = require('bcryptjs');

//查询当前用户信息
router.get('/me', async (req, res) => {
    try {
        const user = await getUser(req)

        success(res, '查询当前用户成功', { user });
    } catch (error) {
        failure(res, error);
    }
})

//更新当前用户信息
router.put('/info', async (req, res) => {
    try {
        const body = {
            nickname: req.body.nickname,
            sex: req.body.sex,
            company: req.body.company,
            introduce: req.body.introduce,
            avatar: req.body.avatar,
        }

        const user = await getUser(req)
        await user.update(body)

        success(res, '更新当前用户信息成功', { user })
    } catch (error) {
        failure(res, error);
    }
})

//更新当前用户敏感信息
router.put('/account', async (req, res) => {
    try {
        const body = {
            username: req.body.username,
            email: req.body.email,
            current_password: req.body.current_password,
            new_password: req.body.new_password,
            passwordConfirmation: req.body.passwordConfirmation,
        }

        if (!body.current_password) {
            throw new BadRequestError('请输入当前密码');
        }
        if (body.new_password !== body.passwordConfirmation) {
            throw new BadRequestError('两次输入的密码不一致');
        }
        const user = await getUser(req,true)
        const isPasswordValid =bcrypt.compareSync(body.current_password, user.password);
        if(!isPasswordValid){
            throw new BadRequestError('当前密码错误');
        }
        await user.update(body)
        delete user.dataValues.password
        success(res, '更新当前用户信息成功', { user })
    } catch (error) {
        failure(res, error);
    }
})

//公用方法：查询当前用户
async function getUser(req, showPassword = false) {
    const id = req.userId
    let condition = {}
    if (!showPassword) {
        condition = {
            attributes: { exclude: ['password'] }
        }
    }

    const user = await User.findByPk(id, condition);
    if (!user) {
        throw new NotFoundError(`用户${id}不存在`);
    }
    return user;
}
module.exports = router;